package com.example.mqttdemo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mqttdemo.entity.pojo.DeviceCommands;
import com.example.mqttdemo.service.DeviceCommandsService;
import com.example.mqttdemo.mapper.DeviceCommandsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
* @author wangzihang
* @description 针对表【device_commands(设备控制记录表)】的数据库操作Service实现
* @createDate 2025-11-11 18:35:19
*/
@Service
@Slf4j
public class DeviceCommandsServiceImpl extends ServiceImpl<DeviceCommandsMapper, DeviceCommands>
    implements DeviceCommandsService{

    @Override
    public void updateResponseData(String deviceId, JSONObject responseData) {
        // 查找最近的待执行或已发送状态的命令
        QueryWrapper<DeviceCommands> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId)
                .in("status", "SENT", "PENDING")
                .orderByDesc("created_time")
                .last("LIMIT 1");
        
        DeviceCommands deviceCommand = this.getOne(queryWrapper);
        
        if (deviceCommand != null) {
            deviceCommand.setResponseData(responseData.toString());
            deviceCommand.setStatus("EXECUTED");
            deviceCommand.setExecutedTime(LocalDateTime.now());
            this.updateById(deviceCommand);
            log.info("更新设备命令响应成功: deviceId={}, commandId={}", deviceId, deviceCommand.getId());
        } else {
            log.warn("未找到待执行的设备命令: deviceId={}", deviceId);
        }
    }
}




